<template>
  <div class="bg-light address-map">
    
    <div class="container-title">
      <div>
        <span>门店及仓库地址</span>
        <span class="normal font-pink">
          (<span style="color:#aa2728">红色</span>显示基础地址，<span style="color:#2781aa">蓝色</span>显示签约扫码地址，
           <span style="color:#19b660">绿色</span>显示仓库扫码地址，<span style="color:#a0a0a0">灰色</span>显示历史生效扫码地址，<span style="color:#ff803c">橙色</span>显示附近门店)
        </span>
      </div>
    </div>
    <Row>
      <Col span="14"> 
        <!-- <Row class="searchAddress fleft">
          <Input type="text" v-model="inputVal" @on-enter='theLocation' /><Button @click="theLocation">查询</Button>
        </Row> -->
        <div class="mapWrap" id="allmap">
        </div>
        <div id="panel" style="display:none"></div>
        <div id="myPageTop">
          <table>
              <tr><td><label>请输入关键字：</label></td></tr>
              <tr><td><input id="tipinput"/></td></tr>
          </table>
      </div>
      </Col>
      <Col span="10" class="pl">
        <!-- <Row class="clickAddr">
          <Col span="4">
            点击坐标：
          </Col>
          <Col span="6" class="mr">
            <Input readonly :value="clickPoint.lng" />
          </Col>-
          <Col span="6" class="ml">
            <Input readonly :value="clickPoint.lat" />
          </Col>
        </Row> -->
        <Row>
          <ul class="storeAddrList">
            <li class="title">
              <span>类型</span><span>坐标</span><span v-if='isEdit'>操作</span>
            </li>
            <li v-for="(item, i) in wareHouse" :key="i">
              <span>{{item.name}}</span><span>{{item.lng}}-{{item.lat}}</span>
              <span v-if='isEdit' @click="wareHouseDel(item)">
                <a v-if='item.type === "wh_place"'>删除</a>
              </span>
            </li>
          </ul>
          <template v-if="isFormStoreCheck">
            <p class="near-store-text font-red big">附近门店(方圆1km)</p>
            <ul class="near-store">
              <li v-for="(item, index) in nearStoreList" :key="index">
                <p>
                  <!-- <span class="font-red mr5" v-if="item.brandName">({{item.brandName}})</span> -->
                  <Tag type="border" color="primary" v-if="item.brandName">{{item.brandName}}</Tag>
                  <span>{{item.storeName}}</span>
                </p>
                <span class="font-blue mr5">距离当前门店{{item.distance}}km</span>
              </li>
            </ul>
          </template>
        </Row>
      </Col>
    </Row>
    <FooterBtns />
  </div>
</template>
<script>
  import FooterBtns from './FooterBtns';
  import { guid, formatFloat } from '@/util'
  const blue_icon = 'https://misc.hzzcckj.cn/skin/icon/map_blue.png';
  const gray_icon = 'https://misc.hzzcckj.cn/skin/icon/map_gray.png';
  const green_icon = 'https://misc.hzzcckj.cn/skin/icon/map_green.png';
  const red_icon = 'https://misc.hzzcckj.cn/skin/icon/map_red.png';
  const orange_icon = 'https://misc.hzzcckj.cn/skin/icon/map_orange.png';

  export default {
    props: {
      form: {
        type: Object
      },
      isEdit: {
        type: Boolean,
        default: true,
      },
      contractId: {
        type: String,
        default: ''
      },
      isFormStoreCheck: {
        type: Boolean,
        default: false
      }
    },
    components: {
      FooterBtns
    },
    computed: {
      contractIdCpt() {
        return  this.contractId || this.$route.query.id
      }
    },
    mounted () {
      this.initPlace()
      setTimeout(() => {
        // this.loadMap();
        this.loadMapIfNotExit().then(() => {
          this.initMap()
          this.getNearStore()
        })
      }, 200)
    },
    data() {
      return {
        map: null,
        inputVal: '',
        clickPoint: {
          lng: 0,
          lat: 0,
        },
        store: {
          lng: 120.32944,
          lat: 30.293894,
          marker: null
        },
        wareHouse: [],
        nearStoreList: []
      }
    },
    methods: {
      getNearStore() {
        let params = {
          distance: 1000
        }
        this.$ajaxGet(`/contract_store/near_store_list/${this.contractIdCpt}`, params).then(res => {
          this.nearStoreList = (res || []).map(item => {
            return {
              ...item,
              distance: formatFloat(item.distance / 1000)
            }
          })
          res.forEach((item) => {
            this.addMarker([item.lng, item.lat], orange_icon, item.storeName, { zIndex: 10 })
          })
        })
      },
      initPlace() { // org_scan_place
        // 保存基础地址
        this.wareHouse.push({ uuid: guid(), type: 'base_place', name: '基础地址', lng: this.form.storeDTO.storeLongitude || '', lat: this.form.storeDTO.storeLatitude || ''})
        this.wareHouse = this.wareHouse.concat((this.form.storeContractDTO.storeContractScanAddressDTOList || []).map(item => {
          return {
            type: item.type == 1 ? 'wh_place' : 'scan_place',
            name: item.typeStr,
            uuid: guid(),
            lng: item.lng,
            lat: item.lat,
            id: item.id,
            adcode: item.adcode
          }
        })).concat((this.form.storeContractScanAddressLogDTOList || []).map(item => {
            item.uuid = guid()
            item.type = 'org_place'
            item.name = '历史生效地址'
            return item
        }))
      },
      // 高德地图
      loadMapIfNotExit() {
        return new Promise((resolve) => {
          if (!window.AMap) {
            var url = 'https://webapi.amap.com/maps?v=1.4.15&key=fe7c4c62bb72d82db42e724fb23122d1&plugin=AMap.Geocoder,AMap.Scale,AMap.ToolBar,AMap.Autocomplete,AMap.PlaceSearch&callback=onLoad'
            var jsapi = document.createElement('script')
            jsapi.charset = 'utf-8'
            jsapi.src = url
            document.head.appendChild(jsapi)
            window.onLoad = function () {
              resolve()
            }
            // let cssUrl = 'https://cache.amap.com/lbs/static/main1119.css'
            // let cssApi = document.createElement('link')
            // cssApi.setAttribute('rel', 'stylesheet')
            // cssApi.href = cssUrl
            // document.head.appendChild(cssApi)
          } else {
            resolve()
          }
        })
      },
      initMap() {
        let _this = this
        let point = this.wareHouse.find(item => item.type === 'base_place')
        let scale = new AMap.Scale({
            visible: true
        })
        let toolBar = new AMap.ToolBar({
            visible: true
        })
        this.map = new window.AMap.Map('allmap', {
          resizeEnable: false,
          scrollWheel: true,
          center: [point.lng, point.lat],
          zoom: 16
        })
        this.initSearch()
        this.map.addControl(scale)
        this.map.addControl(toolBar)
        this.wareHouse.forEach((item, idx) => {
          if (item.type == 'base_place') {
            item.marker = this.addMarker([item.lng, item.lat], red_icon, '基础地址', { idx, zIndex: 100 })
          } else if (item.type == 'scan_place') {
            item.marker = this.addMarker([item.lng, item.lat], blue_icon, '签约扫码地址', { idx, zIndex: 100 })
          } else if (item.type == 'wh_place') {
            let marker = this.addMarker([item.lng, item.lat], green_icon, '仓库地址', { draggable: true, idx, zIndex: 100 })
            item.marker = marker
            marker.on('dragend', function (e) {
              setTimeout(() => {
                if (item.id) {
                  let orgAddress = _this.form.storeContractDTO.storeContractScanAddressDTOList.find(s => s.id === item.id)
                  orgAddress.lng = e.lnglat.lng
                  orgAddress.lat = e.lnglat.lat
                }
              }, 100)
              let wareHouseItem = _this.wareHouse.find(w => w.uuid === item.uuid)
              wareHouseItem.lng = e.lnglat.lng
              wareHouseItem.lat = e.lnglat.lat
            })
            this.addDelCtm(item, this.map, marker)
          } else {
            item.marker = this.addMarker([item.lng, item.lat], gray_icon, '历史生效', { idx });
          }
        })
        if (this.isEdit) {
          this.gdContextMenu(this.map);
        }
        this.getClickPointer()
      },
      initSearch() {
        let autoOptions = {
            input: "tipinput"
        };
        let auto = new AMap.Autocomplete(autoOptions);
        let placeSearch = new AMap.PlaceSearch({
            map: this.map
        });  //构造地点查询类
        AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
        function select(e) {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);  //关键字查询查询
        }
      },
      addMarker (point, imgurl, name, params) {
        let _this = this
        let p = {
          position: point
        }
        if (imgurl) {
          p.icon = imgurl
        }
        let mk = new window.AMap.Marker({
          ...p,
          ...params
        })
        this.map.add(mk)
        mk.setLabel({
          offset: new window.AMap.Pixel(-6, -22),
          content: name
        })
        // mk.on('click', (e) => {
        //   _this.map.setZoomAndCenter(15, [e.lnglat.lng, e.lnglat.lat])
        // })
        return mk
      },
      addDelCtm(item, map, marker) {
        var contextMenu = new window.AMap.ContextMenu();
        contextMenu.addItem("删除地址", ()=> {
            this.wareHouseDel(item)
        }, 0);
        let lnglat =  new AMap.LngLat(item.lng, item.lat);
        marker.on('rightclick', (e)=> {
          contextMenu.open(map, e.lnglat);
          // lnglat = [e.lnglat.lng, e.lnglat.lat]
        })
        // contextMenu.open(map, lnglat);
      },
      // 注册菜单
      gdContextMenu(map) {
        let _this = this
        let contextMenuPositon = null
        let lnglat = new AMap.LngLat(116.397, 39.918);
        let contextMenu = new window.AMap.ContextMenu();
        // contextMenu.addItem("放大一级", function () {
        //   map.zoomIn();
        // }, 0);

        // //右键缩小
        // contextMenu.addItem("缩小一级", function () {
        //   map.zoomOut();
        // }, 1);
        contextMenu.addItem("设置地址到此位置", (e)=> {
          contextMenu.hide()
          let marker = _this.addMarker(contextMenuPositon, green_icon, '仓库地址', { draggable: true })
          marker.on('dragend', function (e) {
            let item = _this.wareHouse.find(item => item.marker === marker)
            item.lng = e.lnglat.lng
            item.lat = e.lnglat.lng
          })
          let lnglat = [contextMenuPositon.lng, contextMenuPositon.lat]
          let geocoder = new window.AMap.Geocoder({ city: '' });
          geocoder.getAddress(lnglat, (status, result) => {
            if (status === 'complete' && result.regeocode) {
                var address = result.regeocode.addressComponent;
                let detailAddress = address.province + (address.city || '') + (address.district || '') + (address.street || '') + (address.streetNumber || '')
                let point = { ...contextMenuPositon, adcode: address.adcode, address: detailAddress }
                let item = _this.addPlace(point, marker)
                setTimeout(() => {
                  // 添加右键删除菜单
                  _this.addDelCtm(item, _this.map, marker)
                }, 300)
            }
          });
        }, 0);
        //地图绑定鼠标右击事件——弹出右键菜单
        map.on('rightclick', function (e) {
            contextMenu.open(map, e.lnglat);
            contextMenuPositon = e.lnglat;
        });
        contextMenu.open(map, lnglat);
      },
      addPlace(point, marker) {
        let uuid = guid()
        let item = {
          uuid,
          type: 'wh_place',
          lng: point.lng,
          lat: point.lat,
          adcode: point.adcode,
          address: point.address,
          marker: marker,
          name:`仓库扫码地址`
        }
        this.wareHouse.push(item)
        this.form.storeContractDTO.storeContractScanAddressDTOList.push({
          uuid,
          type: 1,
          adcode: point.adcode,
          lng: point.lng,
          lat: point.lat,
          address: point.address
        })
        return item
      },
      wareHouseDel(item) {
        if (item.type != 'wh_place') return;
        if (this.wareHouse.length <= 1) {
          this.$Message.info('至少保留一个地址');
          return;
        }
        this.confirmDel(item);
      },
      confirmDel(item) {
        this.$Modal.confirm({
          title: "删除",
          content: "确定删除当前仓库？",
          onOk: () => {
            item.marker.hide();
            this.wareHouse = this.wareHouse.filter(e => e.uuid !== item.uuid)
            let list = this.form.storeContractDTO.storeContractScanAddressDTOList.filter(e => {
              return e.uuid !== item.uuid && e.id !== item.id
            })
            this.form.storeContractDTO.storeContractScanAddressDTOList = list
          }
        });
      },
      theLocation() {
        window.AMap.service(['AMap.PlaceSearch'], () => {
            // 构造地点查询类
            var placeSearch = new window.AMap.PlaceSearch({
                pageSize: 5, // 单页显示结果条数
                pageIndex: 1, // 页码
                citylimit: false, // 是否强制限制在设置的城市内搜索
                map: this.map // 展现结果的地图实例
            });
            // 关键字查询
            placeSearch.search(this.inputVal);
        });
      },
      getClickPointer () {
          this.map.on('click', (e) => {
              this.clickPoint.lat = e.lnglat.lat;
              this.clickPoint.lng = e.lnglat.lng;
          })
      },
    }
  }
</script>
